package 代码随想录.哈希表.两数之和;

import java.security.Key;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;

/**lc：1.两数之和
 * link：https://leetcode-cn.com/problems/two-sum/
 * @author ChenweiLin
 * @create 2021-12-15 11:54
 */
public class TwoSum {
    public static void main(String[] args) {
        int[] nums = new int[]{2,7,11,15};
        int target = 9;
        int[] ints = twoSum(nums, target);
        for (int anInt : ints) {
            System.out.print(anInt + " ");
        }

    }

    //题解思路一：哈希表存储值与下标
    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> sumMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int temp = target-nums[i];//对应数
            if(sumMap.containsKey(temp)){//找到了
                result[0] = i;
                result[1] = sumMap.get(temp);
                break;
            }
            //没找到存入下标
            sumMap.put(nums[i], i);
        }
        return result;

    }

}
